package com.sixth.service.impl;


import com.sixth.bean.MarketStorage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sixth.bean.MarketStorageExample;
import com.sixth.bean.common.BasePageInfo;
import com.sixth.bean.common.BasePageInfoVo;
import com.sixth.bean.common.BaseRespVo;
import com.sixth.constant.Constant;
import com.sixth.constant.PropertiesConstant;
import com.sixth.mapper.MarketStorageMapper;
import com.sixth.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @author qys
 * @Description
 * @date 2022/9/7 16:18

/**
 * @since 2022/09/07 19:33
 * @author zhaoxiangyang
 */
@Service
public class StorageServiceImpl implements StorageService {
    @Autowired
    MarketStorageMapper marketStorageMapper;
    @Autowired
    PropertiesConstant propertiesConstant;
    static String wxStorageFetch = "/wx/storage/fetch/";

    /**
     *
     * @author qys
     * @date 2022/9/7 19:02
     * @param marketStorage
     * @return MarketStorage
     */
    @Override
    public MarketStorage adminStorageCreate(MarketStorage marketStorage) {
        int insert = marketStorageMapper.insert(marketStorage);
        return marketStorage;
    }

    @Override
    public BasePageInfoVo<MarketStorage> query(String key, String name, BasePageInfo info) {
        PageHelper.startPage(info.getPage(),info.getLimit());
        MarketStorageExample marketStorageExample = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = marketStorageExample.createCriteria();
        //key=;namelike;
        if(key != null && !"".equals(key)){
            criteria.andKeyEqualTo(key);
        }
        if(name !=null && !"".equals(name)){
            criteria.andNameLike("%"+name+"%");
        }
        // 修复错误； 查询逻辑删除为false的结果
        criteria.andDeletedEqualTo(false);
        marketStorageExample.setOrderByClause(info.getSort() + " " + info.getOrder());
        List<MarketStorage> marketStorages = marketStorageMapper.selectByExample(marketStorageExample);
        //2022-09-09 16:27尝试修复url查询缺少IP和port错误
         String urlIpPort = "http://" + Constant.SERVER_IP + ":" +Constant.SERVER_PORT;
//        String urlIpPort = "http://" + Constant.SERVER_IP + ":" + Constant.SERVER_PORT_EIGHT_ZERO_EIGHT_THREE;
        for (MarketStorage marketStorage : marketStorages) {
            String url = urlIpPort + marketStorage.getUrl();
            marketStorage.setUrl(url);
        }

        PageInfo<MarketStorage> marketStoragePageInfo = new PageInfo<>(marketStorages);

        long total = marketStoragePageInfo.getTotal();
        int pages = marketStoragePageInfo.getPages();
        // int size = marketStorages.size();
        Integer limit = info.getLimit();
        Integer page = info.getPage();
        BasePageInfoVo<MarketStorage> marketStorageBasePageInfoVo = new BasePageInfoVo<>(total, pages, limit, page,
                marketStorages);
        return marketStorageBasePageInfoVo;
        // BasePageInfoVo<MarketStorage> basePageInfoVo = new BasePageInfoVo<>(marketStorages);
        // return BasePageInfoVo.;
    }

    @Override
    public MarketStorage update(MarketStorage oldMarketStorage) {
        oldMarketStorage.setUpdateTime(new Date());
        // 仅需更新name，updatetime；注意`key`,`type`,`size`;// 如果逻辑删除为true，则不会有编辑按钮和update请求
        int code = marketStorageMapper.updateByPrimaryKeySelective(oldMarketStorage);
        if(code != Constant.ONE){
            return null;
        }
        MarketStorage marketStorage = marketStorageMapper.selectByPrimaryKey(oldMarketStorage.getId());
        return marketStorage;
    }

    @Override
    public int delete(MarketStorage deleteMarketStorage) {
        deleteMarketStorage.setDeleted(true);
        int i = marketStorageMapper.updateByPrimaryKeySelective(deleteMarketStorage);
        if(i != Constant.ONE){
            return Constant.NON;
        }
        return Constant.OK ;
    }


    @Transactional
    @Override
    public MarketStorage wxStorageUpload(MultipartFile file) {
        // 参数封装
        long size = file.getSize();
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setName(originalFilename);
        marketStorage.setType(contentType);
        marketStorage.setSize(((int) size));
        marketStorage.setDeleted(Constant.EXIST);
        // 随机生成文件名
        UUID uuid = UUID.randomUUID();
        int index = originalFilename.lastIndexOf(".");
        String key = new StringBuffer().append(uuid).append(originalFilename.substring(index)).toString();
        marketStorage.setKey(key);
        // url拼接
        String url = "http://" + Constant.SERVER_IP + ":" + Constant.SERVER_PORT + wxStorageFetch + key;
        marketStorage.setUrl(url);
        marketStorageMapper.insertSelective(marketStorage);
        // 文件下载
        File directory = new File(propertiesConstant.getFileupload());
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File uploadFile = new File(directory, key);
        // TODO: 文件过大会报异常
        try {
            file.transferTo(uploadFile);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return marketStorage;
    }
}
